package edu.netjava.ServerCharThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class ChaterDeal extends Thread {

	int port;
	Socket client;
	boolean isConnected = false;
	boolean isStop = false;
	String name;

	public ChaterDeal(Socket client) {
		this.client = client;
	}

	/**
	 * 
	 */
	public void run() {
		
		
		processWriting();
		isStop = true;


	}
	
	
	public void SendMessage(String msg){
		
		try {
			if(isConnected){
				
				OutputStream os = client.getOutputStream();
				msg += "\r\n";
				os.write(msg.getBytes());
				os.flush();
				
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * deal the information between server and client
	 */
	public void processWriting(){
		
		
		try {

			String clientWrite = "";
			String name;
			boolean contine = false;
			while (!contine) {

				clientWrite = "Welcome client from "
						+ client.getRemoteSocketAddress() + "\r\n";

				InputStream is = client.getInputStream();
				OutputStream os = client.getOutputStream();
//				DataInputStream dis = new DataInputStream(is);
//				DataOutputStream dos = new DataOutputStream(os);
				InputStreamReader isr = new InputStreamReader(is,"GBK");
				BufferedReader dis = new BufferedReader(isr);

				os.write(clientWrite.getBytes());
				clientWrite = "Give your name and Say Something...\r\n";
				os.write(clientWrite.getBytes());
				os.write("Set your name:".getBytes());
				name = dis.readLine()+":";
				os.write("You could talk now:".getBytes());
				isConnected = true;

				while (!clientWrite.equalsIgnoreCase("bye")) {
					clientWrite = clientWrite + dis.readLine();

					String clientSay = "\nComing from "
							+ client.getRemoteSocketAddress()
							+ " Clinet : \r\n";
					clientSay += clientWrite + "\n\r";

					System.out.println(clientSay);
					ChaterThreadStore.send2All(clientSay);
					ChaterThreadStore.remove();
////					os.write(clientSay.getBytes());
//
//					os.flush();
				}

				os.write("Connection is Shut off!".getBytes());
				os.flush();
				contine = true;
				client.close();
				dis.close();
//				dos.close();
				is.close();
				os.close();

			}

		} catch (Exception e) {

			e.printStackTrace();
			isConnected = false;
		}
		isConnected = false;
		
	}
	
	public boolean isStop(){
		return this.isStop;
	}

}
